package com.uyayo.oms.shiro;

import com.uyayo.framework.web.util.WebUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


public class ManagerLoginFilter extends AccessControlFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		
		Subject subject = getSubject(request, response);  
	       
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
		if (subject.getPrincipal() != null || isLoginRequest(request, response)) {  
			return Boolean.TRUE;
		}
		 
		if (WebUtil.isAjax(request)) {// ajax请求
			Map<String,String> resultMap = new HashMap<>();
			httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
			resultMap.put("login_status", "401");
			resultMap.put("message", "您尚未登录或登录时间过长,请重新登录!");//当前用户没有登录！
			WebUtil.out(response, resultMap);
		}
		return Boolean.FALSE ;
            
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
			throws Exception {
		//保存Request和Response 到登录后的链接
		saveRequestAndRedirectToLogin(request, response);
		return Boolean.FALSE ;
	}
	
}
